import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Link } from 'react-router'
import cn from 'classnames'
import { Table, Spin, Form, Row, Col, Input, Button, Modal, message, Icon, Popconfirm } from 'antd'

import Ajax from 'lib/Ajax'
import DicTable from './components/dicTable'

const FormItem = Form.Item;

const tabsStyle = {
  display: 'block',
  height: 37
}

class ModuleName extends Component {
	constructor(props) {
    super(props);
    this.state = {
      dicTypes: [],
      dicTypeSelected: {},
      dicTypeSelectedIndex: 0,
      classLoading: true,
      visible: false,
      editType: "",
      rowdata: {}
    }
  }

  componentDidMount(){
    var self = this;
  	Ajax({
      url: '/dic/typeList',
      data: {},
      success: function(data){
        self.setState({
          classLoading: false,
          dicTypes: data,
          dicTypeSelected: data[0]
        });
      },
      error: function(error){
        message.error(error);
      }
    });
  }

  createDicType = (type, rowdata)=>{
    if(type == 'edit'){
      this.setState({
        visible: true,
        editType: 'edit',
        rowdata: rowdata
      });
    }else{
      this.setState({
        visible: true,
        editType: 'new'
      });
    }
  }

  doDelete = (id)=>{
    var self = this;
    Ajax({
      url: '/dic/typeDelete',
      data: {
        dicTypeId: id
      },
      success: function(data){
        _.remove(self.state.dicTypes, function(chr){
          return chr.dicTypeId == id;
        })
        if(self.state.dicTypeSelected.dicTypeId == id){
          self.setState({
            dicTypes: self.state.dicTypes,
            dicTypeSelected: self.state.dicTypes[0],
            dicTypeSelectedIndex: 0
          });
        }else{
          self.setState({
            dicTypes: self.state.dicTypes
          });
        }
      },
      error: function(error){
        message.error(error);
      }
    });
  }

  editOk = (type, rowdata)=>{
    var self = this;
    if(type == 'edit'){
      var area = _.find(this.state.dicTypes, function(chr){
        return chr.dicTypeId == rowdata.dicTypeId;
      })
      Object.assign(area, rowdata);
      self.setState({
        visible: false,
        rowdata: {},
        dicTypes: this.state.dicTypes
      });
      message.success('修改记录成功！');
    }else{
      this.state.dicTypes.push(rowdata);
      self.setState({
        visible: false,
        rowdata: {},
        dicTypes: this.state.dicTypes
      });
      message.success('增加记录成功！');
    }
  }
  editCancel = ()=>{
    this.setState({
      visible: false,
      rowdata: {}
    });
  }

  selectedTab = (dicTypeSelected, dicTypeSelectedIndex) => {
    this.setState({
      dicTypeSelected,
      dicTypeSelectedIndex
    });
  }
  
  render() {
    const { dicTypeSelected, dicTypeSelectedIndex } = this.state;
    const tabsStyles = Object.assign({}, tabsStyle, { transform: `translate3d(0px, ${37*this.state.dicTypeSelectedIndex}px, 0px)`})
    return (
    	<div className="dictionary">
        <div style={{width: 195, float: 'left'}}>
          <div style={{ paddingLeft: 15,marginBottom: 3}}>
            <Button type="ghost" icon="plus" onClick={ this.createDicType.bind(this, 'new') }>新建字典类</Button>
          </div>
          <Spin spinning={this.state.classLoading}>
            <div className="ant-tabs ant-tabs-left ant-tabs-vertical ant-tabs-line" style={{minHeight: 100}}>
              <div className="ant-tabs-bar">
                <div className="ant-tabs-nav-container">
                  <div className="ant-tabs-nav-wrap">
                    <div className="ant-tabs-nav-scroll">
                      <div className="ant-tabs-nav ant-tabs-nav-animated">
                        <div className="ant-tabs-ink-bar ant-tabs-ink-bar-animated" style={tabsStyles}></div>
                        {
                          this.state.dicTypes.map(function(dicType,index){
                            return (
                                <div 
                                  key={ dicType.dicTypeId } 
                                  className={cn("ant-tabs-tab", { "ant-tabs-tab-active" : dicType.dicTypeId == dicTypeSelected.dicTypeId })}
                                >
                                  <span onClick={this.selectedTab.bind(this, dicType, index)}>{dicType.dicTypeName}</span>
                                  <div style={{float: 'right'}}>
                                    <Icon type="edit" onClick={ this.createDicType.bind(this, 'edit', dicType) }/>
                                    <Popconfirm placement="top" title="你确定要删除吗?" onConfirm={this.doDelete.bind(this, dicType.dicTypeId)} okText="确定" cancelText="取消">
                                      <Icon type="delete" />
                                    </Popconfirm>
                                  </div>
                                </div>
                              )
                          }.bind(this))
                        }
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </Spin>
        </div>
        <div className="right">
          <DicTable
            dicType={ this.state.dicTypeSelected }
          />
        </div>
        <CreateModule 
          visible={this.state.visible}
          rowdata={this.state.rowdata}
          type={this.state.editType}
          onOk={ this.editOk }
          onCancel={ this.editCancel }
        />
    	</div>
    )
  }
}

function mapStateToProps(state) {
  return {
    
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({  }, dispatch)
}

module.exports = connect(mapStateToProps,mapDispatchToProps)(ModuleName)

class Create extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false
    }
  }

  componentWillReceiveProps(nextProps){
    if(!nextProps.visible){
      this.props.form.resetFields();
    }
  }

  handleCommit = () => {
    var self = this;
    this.props.form.validateFields((err, values) => {
      if(err == null){
        self.setState({
          loading: true
        });
        const { type, rowdata } = this.props;
        if(self.props.type == 'edit'){
          values.dicTypeId = rowdata.dicTypeId
        }
        Ajax({
          url: '/dic/typeSave',
          data: values,
          success: function(data){
            self.setState({
              loading: false
            });
            self.props.onOk(self.props.type, data);
          },
          error: function(error){
            self.setState({
              loading: false
            });
            message.error(error);
          }
        });
      }
    });
  }

  onCancel = ()=>{
    this.setState({
      loading: false
    });
    this.props.onCancel();
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 19 },
    };
    const { visible, type, rowdata  } = this.props;
    return (<Modal 
              title={ type == 'edit'?"编辑字典类别":"新建字典类别" } 
              visible={visible}
              onOk={ this.handleCommit } 
              onCancel={ this.onCancel }
              okText="确定" 
              cancelText="取消"
            >
              <Spin spinning={this.state.loading}>
                <Form
                  horizontal
                >
                  <Row gutter={20}>
                    {type == 'edit'?(
                      <Col span={24}>
                        <FormItem {...formItemLayout} label="字典类别ID">
                          {getFieldDecorator("dicTypeId",{
                            initialValue: rowdata.dicTypeId,
                            rules: [{
                              required: true, message: '请输入字典类别ID',
                            }]
                          })(
                            <Input disabled/>
                          )}
                        </FormItem>
                      </Col>
                    ):(null)}
                    <Col span={24}>
                      <FormItem {...formItemLayout} label="字典类别">
                        {getFieldDecorator("dicTypeName",{
                          initialValue: type == 'edit'?rowdata.dicTypeName:"",
                          rules: [{
                            required: true, message: '请输入字典类别',
                          }]
                        })(
                          <Input />
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                </Form>
              </Spin>
            </Modal>);
  }
}
var CreateModule = Form.create()(Create);
